#include "sendMessageCommand.h"

QDomDocument SendMessageCommand::run(QDomDocument doc) {
    QDomDocument xmlDocument;
    QString result;

    if (this->isAuthorized(doc)) {
        User* me = this->getCurrentUser(doc);
        QDomNodeList roomNodes = doc.elementsByTagName("room");
        QDomNodeList textNodes = doc.elementsByTagName("text");
        if (roomNodes.count() == 1 && textNodes.count() == 1) {
            QString roomName = roomNodes.at(0).toElement().text().trimmed();
            QString text = textNodes.at(0).toElement().text().trimmed();
            Room* room = DB::getInstance()->findRoom(roomName);
            result = this->process(me, room, text);
        } else {
            result = "<sendMessage><success>FALSE</success><reason>WRONG_XML</reason></sendMessage>";
        }
    } else {
        result = "<sendMessage><success>FALSE</success><reason>NOT_AUTHORIZED</reason></sendMessage>";
    }

    xmlDocument.setContent(result);
    return xmlDocument;
}


QString SendMessageCommand::process(User* me, Room* room, QString text) {
    QString result;
    if (room == NULL) {
        result = "<sendMessage><success>FALSE</success><reason>NO_SUCH_ROOM</reason></sendMessage>";
    } else {
        if (room->isMember(me)) {
            if (!text.isEmpty()) {
                Message* message = new Message(room, me, text);
                room->addMessage(message);
                result = "<sendMessage><success>TRUE</success></sendMessage>";
            } else {
                result = "<sendMessage><success>FALSE</success><reason>MESSAGE_EMPTY</reason></sendMessage>";
            }
        } else {
           result = "<sendMessage><success>FALSE</success><reason>YOU_ARE_NOT_IN_ROOM</reason></sendMessage>";
        }
    }
    return result;
}
